package xyz.itpath.gen.service.impl;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import xyz.itpath.gen.dto.ClassDefine;
import xyz.itpath.gen.dto.ClassField;
import xyz.itpath.gen.dto.Column;
import xyz.itpath.gen.dto.Table;
import xyz.itpath.gen.mapper.GeneralMateMapper;
import xyz.itpath.gen.util.StringUtils;
import xyz.itpath.gen.util.TypeMapUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhaom
 * @date 2021/9/23 - 20:49
 * <br/>
 * MyBatisPlus实现
 */
@Service
@ConditionalOnProperty(prefix = "type", name = "dao", havingValue = "mybatis-plus", matchIfMissing = true)
public class MyBatisPlusImpl extends AbstractGeneratorServiceImpl {

    private final GeneralMateMapper generalMateMapper;
    private final TypeMapUtils typeMapUtils;

    public MyBatisPlusImpl(GeneralMateMapper generalMateMapper,
                           TypeMapUtils typeMapUtils) {
        this.generalMateMapper = generalMateMapper;
        this.typeMapUtils = typeMapUtils;
    }

    @Override
    public List<Table> listAllTable() {
        return generalMateMapper.listTables();
    }

    @Override
    public List<Column> listColumns(String dbName, String tbName) {
        return generalMateMapper.listColumns(dbName, tbName);
    }

    @Override
    public List<Table> getTableInfo(String dbName, List<String> tbName) {
        if (!tbName.isEmpty()) {
            return generalMateMapper.getTableInfo(dbName, tbName);
        }
        return new ArrayList<>();
    }

    @Override
    public List<ClassDefine> convertTableToClassDefine(String dbName, String tbName, String basePackage) {
        List<Table> tableInfo = getTableInfo(dbName, Collections.singletonList(tbName));
        return tableInfo.stream().map(item -> {
            ClassDefine classDefine = new ClassDefine();
            classDefine.setClassName(StringUtils.underlineToUpperCamel(item.getTableName()));
            classDefine.setLowerClassName(StringUtils.underlineToCamel(item.getTableName()));
            classDefine.setBasePackage(basePackage);
            classDefine.setClassComment(item.getComment());
            List<ClassField> classFields = typeMapUtils.convertColumnToField(listColumns(dbName, item.getTableName()));
            classDefine.setClassFields(classFields);
            return classDefine;
        }).collect(Collectors.toList());
    }

}
